﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Labthink.PCSoft.UniversalHost4.Utility
{
    public static class XmlHelper
    {
        public static T LoadFromXml<T>(string filename)
        {
            using TextReader reader = new StreamReader(filename);
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            var serializer = new XmlSerializer(typeof(T), "");
            return (T)serializer.Deserialize(reader);
        }

        public static bool SaveToXml<T>(T obj, string filename)
        {
            try
            {
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                var serializer = new XmlSerializer(typeof(T), "");
                TextWriter writer = new StreamWriter(filename);
                serializer.Serialize(writer,obj, ns);
                return true;
            }
            catch (IOException e)
            {
                return false;
            }
        }

        public static object Clone<T>(T obj)
        {
            using var stream = new MemoryStream();
            var s = new XmlSerializer(typeof(T));
            s.Serialize(stream, obj);
            stream.Flush();

            stream.Seek(0, SeekOrigin.Begin);
            object o = s.Deserialize(stream);
            return o;
        }
    }
}
